package dhu.cst.jnlwt.jiangnan181310209liwanting181310302.tally.activity_tally;

import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;

import android.app.DatePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;


import com.google.android.material.tabs.TabLayout;
import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechRecognizer;
import com.iflytek.cloud.SpeechUtility;
import com.iflytek.cloud.ui.RecognizerDialog;
import com.iflytek.cloud.ui.RecognizerDialogListener;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import dhu.cst.jnlwt.jiangnan181310209liwanting181310302.tally.R;
import dhu.cst.jnlwt.jiangnan181310209liwanting181310302.tally.adapter.MyGridViewAdapter;
import dhu.cst.jnlwt.jiangnan181310209liwanting181310302.tally.adapter.MyPagerAdapter;
import dhu.cst.jnlwt.jiangnan181310209liwanting181310302.tally.database.AccountDao;
import dhu.cst.jnlwt.jiangnan181310209liwanting181310302.tally.entity.AccountBean;
import dhu.cst.jnlwt.jiangnan181310209liwanting181310302.tally.entity.CategoryBean;

public class RecordActivity extends AppCompatActivity implements NumPlateView.OnKeyClickListener{


    private EditText etPlate;
    private EditText etMessage;
    private Button buttonCalendar;
    private ImageButton back;
    private DatePickerDialog datePickerDialog;
    private NumPlateView PlateView;

    private String phoneNumber;
    private CategoryBean categorySelected;
    private TextView hint;

    List<CategoryBean> incomeList;
    List<CategoryBean> foodList;
    List<CategoryBean> shopList;
    List<CategoryBean> trafficList;
    List<CategoryBean> funList;
    List<CategoryBean> houseList;
    List<CategoryBean> otherList;

    private ImageButton listenBtn;
    private String engineType = "cloud";
    private String resultType = "plain";
    private StringBuffer buffer = new StringBuffer();
    private Toast mToast;
    SpeechRecognizer mIat;
    private RecognizerDialog mIatDialog;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_record);
        phoneNumber = getIntent().getStringExtra("phone_toRA");
        SpeechUtility.createUtility(RecordActivity.this, SpeechConstant.APPID +"=5fb40080");


        etPlate = findViewById(R.id.etPlate);
        etMessage = findViewById(R.id.etMessage);
        listenBtn = findViewById(R.id.listenBtn);
        PlateView = findViewById(R.id.plate_view);
        buttonCalendar = findViewById(R.id.btCalender);
        hint = findViewById(R.id.hint_record);
        PlateView.setOnKeyClickListener(this);
        back = findViewById(R.id.record_back);
        mToast = Toast.makeText(this, "", Toast.LENGTH_SHORT);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        //初始化操作
        SpeechUtility.createUtility(this,SpeechConstant.APPID+"=5fb40080");
        //创建SpeechRecognizer对象
        mIat = SpeechRecognizer.createRecognizer(this,mInitListener);
        //创建RecognizerDialog对象
        mIatDialog = new RecognizerDialog(this,mInitListener);
        //设置麦克风按钮的点击事件
        listenBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                buffer.setLength(0);
                etMessage.setText(null);
                setParam();//设置参数
                mIatDialog.setListener(mRecognizerDialogListener);//设置讯飞识别语音后的回调监听
                mIatDialog.show();//显示讯飞语音识别视图
                showTip("请开始说话");
            }
        });

        //禁止金额输入框弹出键盘
        etPlate.setInputType(InputType.TYPE_NULL);
        etPlate.setKeyListener(null);

        buttonCalendar.setText(new SimpleDateFormat("yyyy.MM.dd").format(new Date()));
        //日历按钮点击事件
        buttonCalendar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showCalenderDialog();
            }
        });

        initData();
        initView();
    }

    private void showCalenderDialog() {
        final Calendar calendar = Calendar.getInstance();
        datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                Calendar c = Calendar.getInstance();
                c.set(Calendar.YEAR,year);
                c.set(Calendar.MONTH,monthOfYear);
                c.set(Calendar.DAY_OF_MONTH,dayOfMonth);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");
                buttonCalendar.setText(sdf.format(c.getTime()));
            }
        },
                calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH));
        datePickerDialog.show();
        //自动弹出键盘
        datePickerDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
    }

    public void initData(){
        AccountDao dbManager = new AccountDao(RecordActivity.this,phoneNumber);
        incomeList = dbManager.getCategories("收入");
        foodList = dbManager.getCategories("食物");
        shopList = dbManager.getCategories("购物");
        trafficList = dbManager.getCategories("出行");
        funList = dbManager.getCategories("娱乐");
        houseList = dbManager.getCategories("住房");
        otherList = dbManager.getCategories("其他");
    }

    public void initView(){
        List<View> mViews = new ArrayList<View>();
        TabLayout tabLayout;
        tabLayout = findViewById(R.id.record_tabs);
        tabLayout.setTabMode(TabLayout.MODE_FIXED);

        View pagerIncome = getLayoutInflater().inflate(R.layout.gridview_record,null);
        GridView gridView_income = (GridView)pagerIncome.findViewById(R.id.gridView_record);
        gridView_income.setAdapter(new MyGridViewAdapter(incomeList,this));
        gridView_income.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                categorySelected = incomeList.get(position);

                hint.setText("您选择了："+categorySelected.getCategory());
            }
        });

        View pagerFood = getLayoutInflater().inflate(R.layout.gridview_record,null);
        GridView gridView_food = (GridView)pagerFood.findViewById(R.id.gridView_record);
        gridView_food.setAdapter(new MyGridViewAdapter(foodList,this));
        gridView_food.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                categorySelected = foodList.get(position);
                hint.setText("您选择了："+categorySelected.getCategory());
            }
        });

        View pagerShop = getLayoutInflater().inflate(R.layout.gridview_record,null);
        GridView gridView_shop = (GridView)pagerShop.findViewById(R.id.gridView_record);
        gridView_shop.setAdapter(new MyGridViewAdapter(shopList,this));
        gridView_shop.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                categorySelected = shopList.get(position);
                hint.setText("您选择了："+categorySelected.getCategory());
            }
        });

        View pagerTraffic = getLayoutInflater().inflate(R.layout.gridview_record,null);
        GridView gridView_traffic = (GridView)pagerTraffic.findViewById(R.id.gridView_record);
        gridView_traffic.setAdapter(new MyGridViewAdapter(trafficList,this));
        gridView_traffic.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                categorySelected = trafficList.get(position);
                hint.setText("您选择了："+categorySelected.getCategory());
            }
        });
        View pagerFun = getLayoutInflater().inflate(R.layout.gridview_record,null);
        GridView gridView_fun = (GridView)pagerFun.findViewById(R.id.gridView_record);
        gridView_fun.setAdapter(new MyGridViewAdapter(funList,this));
        gridView_fun.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                categorySelected = funList.get(position);
                hint.setText("您选择了："+categorySelected.getCategory());
            }
        });
        View pagerHouse = getLayoutInflater().inflate(R.layout.gridview_record,null);
        GridView gridView_house = (GridView)pagerHouse.findViewById(R.id.gridView_record);
        gridView_house.setAdapter(new MyGridViewAdapter(houseList,this));
        gridView_house.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                categorySelected = houseList.get(position);
                hint.setText("您选择了："+categorySelected.getCategory());
            }
        });
        View pagerOther = getLayoutInflater().inflate(R.layout.gridview_record,null);
        GridView gridView_other = (GridView)pagerOther.findViewById(R.id.gridView_record);
        gridView_other.setAdapter(new MyGridViewAdapter(otherList,this));
        gridView_other.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                categorySelected = otherList.get(position);
                hint.setText("您选择了："+categorySelected.getCategory());
            }
        });

        mViews.add(pagerIncome);
        mViews.add(pagerFood);
        mViews.add(pagerShop);
        mViews.add(pagerTraffic);
        mViews.add(pagerFun);
        mViews.add(pagerHouse);
        mViews.add(pagerOther);
        ViewPager viewPager = (ViewPager)findViewById(R.id.record_vp);
        viewPager.setAdapter(new MyPagerAdapter(mViews));
        tabLayout.setupWithViewPager(viewPager);
    }

    @Override
    public void onKeyClick(String key) {
        Editable editable = etPlate.getText();
        int start = etPlate.getSelectionStart();
        if (key.equalsIgnoreCase("Del")) {
            if (editable.length() > 0 && start > 0) {
                editable.delete(start - 1, start);
            }
            return;
        }else if (key.equalsIgnoreCase("Reset")) {
            if (editable.length() > 0 && start > 0) {
                editable.delete(0, start);
            }
            return;
        }else if (key.equalsIgnoreCase("Finish")) {
            if (editable.length() > 0 && start > 0) {
                String str=editable.toString();
                if(str.contains("+")==true){
                    //做加法
                    String[]  strs=str.split("\\+");
                    double num1 = Double.parseDouble(strs[0]);
                    double num2 = Double.parseDouble(strs[1]);
                    double num=num1+num2;
                    String money=String.valueOf(num);
                    editable.delete(0, start);
                    editable.insert(0,money);

                }
                else if(str.contains("-")==true){
                    //做减法
                    String[]  strs=str.split("-");
                    double num1 = Double.parseDouble(strs[0]);
                    double num2 = Double.parseDouble(strs[1]);
                    double num=num1-num2;
                    String money=String.valueOf(num);
                    editable.delete(0, start);
                    editable.insert(0,money);
                }
                //插入数据库
                double account = Double.parseDouble(editable.toString());
                String category = categorySelected.getCategory();
                String date = buttonCalendar.getText().toString();
                String postscript = etMessage.getText().toString();
                AccountBean accountItem = new AccountBean(account,category,date,postscript);
                AccountDao dbManager = new AccountDao(RecordActivity.this,phoneNumber);
                if(dbManager.getCategoryType(category)==0){
                    dbManager.addIncomeItem(accountItem);
                }
                else{
                    dbManager.addExpenditureItem(accountItem);
                }
                Intent intent = new Intent(RecordActivity.this,HomeActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                intent.putExtra("phone_toHA",phoneNumber);
                startActivity(intent);
            }
            else{
                Toast.makeText(RecordActivity.this,"金额应大于零",Toast.LENGTH_SHORT).show();
            }
            return;
        }
        else{
            editable.insert(start, key);
        }
    }

    @Override
    public void finish() {
        super.finish();
        Log.d("tag","RecordActivity finish");
    }

    public void setParam() {
        mIat.setParameter(SpeechConstant.CLOUD_GRAMMAR,null );
        mIat.setParameter( SpeechConstant.SUBJECT, null );
        //设置听返回结果格式
        mIat.setParameter(SpeechConstant.RESULT_TYPE, resultType);
        //设置听写引擎
        mIat.setParameter( SpeechConstant.ENGINE_TYPE, engineType );
        //设置语言
        mIat.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
        //设置语言区域
        mIat.setParameter(SpeechConstant.ACCENT, "mandarin");
        //设置语音前端点
        mIat.setParameter(SpeechConstant.VAD_BOS, "4000");
        //设置语音后端点
        mIat.setParameter(SpeechConstant.VAD_EOS, "1000");
        //设置标点符号
        mIat.setParameter(SpeechConstant.ASR_PTT,"0");}


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if( null != mIat ){
            // 退出时释放连接
            mIat.cancel();
            mIat.destroy();
        }
    }
    //提示信息
    private void showTip(final String str) {
        mToast.setText(str);
        mToast.show();
    }

    private InitListener mInitListener = new InitListener() {
        @Override
        public void onInit(int code) {
            Log.d("speech", "SpeechRecognizer init() code = " + code);
            if (code != ErrorCode.SUCCESS) {
                showTip("初始化失败，错误码：" + code+",请点击网址https://www.xfyun.cn/document/error-code查询解决方案");
            }
        }
    };

    private RecognizerDialogListener mRecognizerDialogListener = new RecognizerDialogListener() {
        @Override
        public void onResult(RecognizerResult recognizerResult, boolean b) {
            if(resultType.equals("plain")){
                buffer.append(recognizerResult.getResultString());
                etMessage.setText(buffer.toString());
                etMessage.setSelection(etMessage.length());
            }
        }

        @Override
        public void onError(SpeechError speechError) {
            showTip(speechError.getPlainDescription(true));
        }
    };
}
